---
title: "R Notebook"
output: html_notebook
---

This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. 

Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Cmd+Shift+Enter*. 

```{r}
dataPath <- "data/"
train <- read.csv(paste0(dataPath,"train_sample.csv"))
test <- read.csv(paste0(dataPath,"test_sample.csv"))

m=8 # = ncol(train)
predictors = paste0("X",1:(m-1))
```
```{r}
library(xgboost)
library(randomForest)
```
```{r}
param<-list("objective" = "binary:logistic")

matrHitters = data.matrix(train)[,predictors]
target = train$class

set.seed(1)
cvSalary = xgb.cv(params=param, data = matrHitters, label = target,
                nfold=5, nrounds = 50,prediction=T,verbose=F)
```
```{r}
set.seed(1)
(cvSalary.table<-cvSalary$evaluation_log)
(bestNR = which.min(cvSalary.table$test_error_mean))
```
```{r}
set.seed(1)
modelSalary<-xgboost(data=matrHitters, label = target, params=param,
                     nrounds=bestNR,verbose=F,save_period=NULL)
```

```{r}
predicts <- predict(modelSalary, newdata=data.matrix(test)[,predictors])
pred <- cbind(test$id, as.integer(predicts > 0.5))
```

```{r}
set.seed(1)
rfclass <- randomForest(x=train, y=as.factor(train$class), importance=T)
```

```{r}
importance(rfclass)

importance(rfclass)[which.max(importance(rfclass)[,"MeanDecreaseAccuracy"])]

most = 2
```



```{r}
saveRDS(list(RFMostImportant = most, Forecast = pred), "W4answer.rds")
```

Add a new chunk by clicking the *Insert Chunk* button on the toolbar or by pressing *Cmd+Option+I*.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the *Preview* button or press *Cmd+Shift+K* to preview the HTML file). 

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike *Knit*, *Preview* does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.

